package com.example.chuntiao.cophook.mytools;

import android.app.Activity;
import android.app.Application;
import android.content.Context;
import android.content.SharedPreferences;
import android.os.Handler;

import org.litepal.LitePal;

import java.io.IOException;
import java.io.InputStream;
import java.security.GeneralSecurityException;
import java.security.KeyStore;
import java.security.SecureRandom;
import java.security.cert.CertificateFactory;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import javax.net.ssl.HostnameVerifier;
import javax.net.ssl.SSLContext;
import javax.net.ssl.SSLSession;
import javax.net.ssl.TrustManager;
import javax.net.ssl.TrustManagerFactory;
import javax.net.ssl.X509TrustManager;

import okhttp3.Cookie;
import okhttp3.CookieJar;
import okhttp3.HttpUrl;
import okhttp3.OkHttpClient;

/**
 * Created by chuntiao
 */

public class MyApp extends Application {
    public void setClient(OkHttpClient client) {
        this.client = client;
    }

    private OkHttpClient client;


    private boolean logedIn;
    private Handler mainHandler;

    public Handler getMainHandler() {
        return mainHandler;
    }

    public void setMainHandler(Handler mainHandler) {
        this.mainHandler = mainHandler;
    }

    final private Object lookObj = new Object();

    public final static String LocalHost = "10.201.152.126";
    public final static String RemoteHost = "115.159.107.74";

    public static String HOST_IP = RemoteHost;
    public static String HOST_S_URL = "https://" + HOST_IP + ":8443/cophook/";
    public static String HOST_URL = "http://" + HOST_IP + ":8080/cophook/";
    // public static String HOST_S_URL ="http://"+HOST_IP+":8080/cophook/";

    //private ArrayList<Person> personArrayList;
    //private ArrayList<Org>orgArrayList;
    //private ArrayList<Person> personListToHide=new ArrayList<>();

   /* public ArrayList<Person> getPersonListToHide() {
        return personListToHide;
    }

    public void setPersonListToHide(ArrayList<Person> personListToHide) {
        this.personListToHide = personListToHide;
    }*/

    private long lastSync;
    private long lastLogIn;

    public long getLastLogIn() {
        return lastLogIn;
    }

    public void setLastLogIn(long lastLogIn) {
        this.lastLogIn = lastLogIn;
    }

    private String uid;
    private String passwd;
    private String uname;
    private String phone1;
    private String phone2;
    private String locate;


    public String getImsi() {
        return imsi;
    }

    public void setImsi(String imsi) {
        this.imsi = imsi;
    }

    private String imsi;


    private int imgVer;

    @Override
    public void onCreate() {
        super.onCreate();
        LitePal.initialize(this);
        SharedPreferences sharedPreferences = getSharedPreferences("data", MODE_PRIVATE);
        uid = sharedPreferences.getString("uid", null);
        passwd = sharedPreferences.getString("passwd", null);
        uname = sharedPreferences.getString("uname", null);
        phone1 = sharedPreferences.getString("phone1", "");
        imgVer = sharedPreferences.getInt("img_ver", -1);
        phone2 = sharedPreferences.getString("phone2", "");
        locate = sharedPreferences.getString("locate", null);


        lastSync = sharedPreferences.getLong("last_sync", 0L);
        lastLogIn = sharedPreferences.getLong("last_login", 0L);
        logedIn = sharedPreferences.getBoolean("logedin", false);
        imsi = sharedPreferences.getString("imsi", null);

        String ip = sharedPreferences.getBoolean("is_lan", false) ? LocalHost : RemoteHost;
        setHostIp(ip);

        try {
            client = prepareClient(getAssets().open("wang_tomcat_server_online.cer"));
        } catch (GeneralSecurityException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    @Override
    public void onTerminate() {
        super.onTerminate();
        setClient(null);
    }

    public Object getLookObj() {
        return lookObj;
    }

    public String getPhone1() {
        return phone1;
    }

    public void setPhone1(String phone1) {
        this.phone1 = phone1;
    }

    public OkHttpClient getClient() {
        return client;
    }


    public boolean isLogedIn() {
        return logedIn;
    }

    public void setLogedIn(boolean logedIn) {
        this.logedIn = logedIn;
    }

    public long getLastSync() {
        return lastSync;
    }

    public synchronized void setLastSync(long lastSync) {
        this.lastSync = lastSync;
    }

    public String getUid() {
        return uid;
    }

    public void setUid(String uid) {
        this.uid = uid;
    }

    public String getPasswd() {
        return passwd;
    }

    public void setPasswd(String passwd) {
        this.passwd = passwd;
    }

    public String getUname() {
        return uname;
    }

    public void setUname(String uname) {
        this.uname = uname;
    }

    public int getImgVer() {
        return imgVer;
    }

    public void setImgVer(int imgVer) {
        this.imgVer = imgVer;
    }

    public boolean timeToSyn() {
        if (System.currentTimeMillis() - lastSync > 1000L * 60 * 60 * 24 * 1.15)
            return true;
        return false;// TODO 测试断网情况下对数据的保护
    }

    public String getPhone2() {
        return phone2;
    }

    public void setPhone2(String phone2) {
        this.phone2 = phone2;
    }

    public String getLocate() {
        return locate;
    }

    public void setLocate(String locate) {
        this.locate = locate;
    }

    public OkHttpClient prepareClient(InputStream certificate) throws GeneralSecurityException, IOException {

        CertificateFactory cf = CertificateFactory.getInstance("X.509");
        KeyStore keyStore = KeyStore.getInstance(KeyStore.getDefaultType());

        keyStore.load(null, null);
        keyStore.setCertificateEntry("ca", cf.generateCertificate(certificate));
        if (certificate != null)
            certificate.close();

        SSLContext sslContext = SSLContext.getInstance("TLS");

        TrustManagerFactory trustManagerFactory =
                TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm());

        trustManagerFactory.init(keyStore);
        sslContext.init
                (
                        null,
                        trustManagerFactory.getTrustManagers(),
                        new SecureRandom()
                );

        TrustManager[] trustManagers = trustManagerFactory.getTrustManagers();
        X509TrustManager x509tm = null;
        if (trustManagers[0] instanceof X509TrustManager)
            x509tm = (X509TrustManager) (trustManagers[0]);

        client = new OkHttpClient.Builder()
                .hostnameVerifier(new HostnameVerifier() {
                    @Override
                    public boolean verify(String hostname, SSLSession session) {//必须重写这个方法,可能因为我用的 hostname 直接是 IP 地址或者使用了自签名证书
                        return MyApp.HOST_IP.equals(hostname);
                    }
                })
                .sslSocketFactory(sslContext.getSocketFactory(), x509tm)
                .cookieJar(new CookieJar() {
                    private final HashMap<String, List<Cookie>> cookieStore = new HashMap<>();

                    @Override
                    public void saveFromResponse(HttpUrl url, List<Cookie> cookies) {
                        cookieStore.put(url.host(), cookies);
                    }

                    @Override
                    public List<Cookie> loadForRequest(HttpUrl url) {
                        List<Cookie> cookies = cookieStore.get(url.host());
                        return cookies != null ? cookies : new ArrayList<Cookie>();
                    }
                })
                .build();

        return client;

    }

    public static void setHostIp(String ip) {
        HOST_IP = ip;
        HOST_S_URL = "https://" + HOST_IP + ":8443/cophook/";
        HOST_URL = "http://" + HOST_IP + ":8080/cophook/";
    }
    public void setNextUpdate(){
        setLastSync(0L);
        SharedPreferences.Editor editor=getSharedPreferences("data",MODE_PRIVATE).edit();
        editor.putLong("last_sync",0L);
        editor.apply();
    }

}
